<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div style="margin: 10px 0px; display: flex; gap: 10px; align-items: center;">
				<el-select v-model="data.schoolId" placeholder="请选择学校" style="width: 200px" @change="handlerSchoolChange">
					<el-option v-for="item in data.schoolList" :key="item.id" :label="item.schoolName" :value="item.id"></el-option>
				</el-select>
				<el-date-picker
					style="width: 200px"
					v-model="data.dateTime"
					format="YYYY[年第]ww[周]"
					type="week"
					size="mini"
					@change="handlerDateChange"
					placeholder="选择开始时间"
				>
				</el-date-picker>
			</div>
			<el-row>
				<div class="mb8" style="width: 100%">
					<el-button icon="folder-add" type="primary" class="ml10" @click="comboInfoDialogRef.openDialog(data.comboId, '', data.schoolId)" :disabled="!data.schoolId"> 新增 </el-button>
					<el-button type="primary" class="ml10" @click="handlerCopyCombo(data.comboId)" :disabled="!data.schoolId"> 复制上周套餐到下周 </el-button>
				</div>
			</el-row>
			<el-table
				size="mini"
				:cell-style="{ textAlign: 'center' }"
				:header-cell-style="{ background: '#F4F4F4', textAlign: 'center' }"
				:data="data.tableData"
				:max-height="800"
				border
				style="width: 100%"
			>
				<template v-for="(col, index) in data.dateList">
					<el-table-column :prop="col.date" :label="col.date + '(' + col.week + ')'" min-width="200px">
						<template #default="scope">
							<el-card v-if="scope.row[col.date]" @click="comboInfoDialogRef.openDialog(data.comboId, scope.row[col.date].id, data.schoolId)">
								<div class="combo-item">
									<img class="combo-image" :src="baseURL + scope.row[col.date].pics" />
									<div class="combo-dishName">{{ scope.row[col.date].dishName }}</div>
								</div>
							</el-card>
						</template>
					</el-table-column>
				</template>
			</el-table>
		</div>
		<ComboInfoDialog ref="comboInfoDialogRef" @refresh="handlerDateChange"></ComboInfoDialog>
	</div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router';
import { listDate, delObj, copyCombo } from '/@/api/school/dateCombo';
import { listAll as listAllSchool } from '/@/api/school/school';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';
const data = reactive({
	comboId: null,
	schoolId: '',
	dateTime: [],
	dateList: [],
	tableData: [],
	schoolList: [],
});
const route = useRoute();
const comboInfoDialogRef = ref();
const ComboInfoDialog = defineAsyncComponent(() => import('./form.vue'));
onMounted(async () => {
	data.comboId = route.query.comboId;

	// 获取学校列表
	await getSchoolList();

	// 获取当前日期
	const today = dayjs();
	const startOfWeek = today.startOf('week');
	data.dateTime = startOfWeek;

	// 如果有学校，默认选择第一个
	if (data.schoolList.length > 0) {
		data.schoolId = data.schoolList[0].id;
		getDays(startOfWeek);
	}
});

// 获取学校列表
const getSchoolList = async () => {
	try {
		const resp = await listAllSchool();
		data.schoolList = resp.data;
	} catch (error) {
		console.error('获取学校列表失败:', error);
		ElMessage.error('获取学校列表失败');
	}
};

// 学校变更处理
const handlerSchoolChange = () => {
	if (data.schoolId && data.dateTime) {
		getDays(dayjs(data.dateTime));
	}
};

const handlerDateChange = () => {
	if (data.schoolId) {
		getDays(dayjs(data.dateTime));
	}
};

const handlerCopyCombo = async (comboId: string) => {
	//获取所选周的周二
	const startOfWeek = dayjs(data.dateTime).startOf('week').add(1, 'day');
	//转化为YYYY-MM-DD
	const dateTime = startOfWeek.format('YYYY-MM-DD');

	await copyCombo(comboId,{currentDate: dateTime});
	ElMessage.success('复制成功');
	handlerDateChange();
};

const getDays = (startTime: any) => {
	const endTime = startTime.add(6, 'day');
	// 初始化日期
	let currentDate = startTime;
	// 存储每一天的日期
	const dates = [];
	// 循环获取每一天的日期
	const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	while (currentDate.isSameOrBefore(endTime)) {
		// 获取星期几（0 表示周日，1 表示周一）
		const dayOfWeek = currentDate.day();
		dates.push({
			date: currentDate.format('YYYY-MM-DD'),
			week: daysOfWeek[dayOfWeek],
		});
		currentDate = currentDate.add(1, 'day');
	}

	data.dateList = dates;
	getDateList();
};

const getDateList = async () => {
	if (!data.schoolId) {
		data.tableData = [];
		return;
	}

	const resp = await listDate({
		comboId: data.comboId,
		schoolId: data.schoolId,
		startTime: data.dateList[0].date,
		endTime: data.dateList[data.dateList.length - 1].date
	});
	data.tableData = resp.data;
	console.log(data.tableData);
};
</script>

<style scoped lang="scss">
.combo-item {
	display: flex;
	cursor: pointer;
	gap: 10px;
	min-width: 300px;
	.combo-image {
		width: 50px;
		height: 50px;
		border-radius: 5px;
	}
}
</style>
